{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "https://mp.weixin.qq.com/s?__biz=MzkxODE3NjExOQ==&mid=2247485429&idx=1&sn=72401e68d766bc500cda96852523a96b&chksm=c1b42fedf6c3a6fbbc18bbc4b5c2abcdb7cdfa489c043c7e78ea38e3972ec0a7ece5bdc98b69&scene=178&cur_album_id=3354758663365918722#rd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入需要使用的库\n",
    "import akshare as ak\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "# 关闭警告信息\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "# 获取沪深300指数10年的收盘价数据\n",
    "start_date = '20140101'  # 开始日期\n",
    "end_date = '20231229'  # 结束日期\n",
    "bars = ak.stock_zh_index_hist_csindex(symbol='000300', start_date=start_date, end_date=end_date)\n",
    "prices = bars[['日期','收盘']]\n",
    "# 将日期设置为datetime格式\n",
    "prices['日期'] = pd.to_datetime(prices['日期'])\n",
    "prices = prices.set_index('日期')\n",
    "# 计算日收益率\n",
    "returns = prices['收盘'].pct_change()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算夏普比率：用简单年化收益率\n",
    "rf = 0.0  # 无风险利率设为0\n",
    "annual_periods = 244  # 年化期数，一年约244个交易日\n",
    "# 计算超额收益\n",
    "returns = returns - rf\n",
    "# 简单年化收益率 = 投资组合的平均超额收益率 * 年化期数\n",
    "return_mean = np.mean(returns) * annual_periods\n",
    "# 计算年化标准差\n",
    "std_annualized = returns.std() * np.sqrt(annual_periods)\n",
    "# 计算夏普比率\n",
    "sharpe = return_mean / std_annualized"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算夏普比率：用复合年化收益率\n",
    "rf = 0.0  # 无风险利率设为0\n",
    "annual_periods = 244  # 年化期数，一年约244个交易日\n",
    "# 计算超额收益\n",
    "returns = returns - rf\n",
    "# 计算年化收益率\n",
    "years = len(returns) / annual_periods  # 投资年数\n",
    "total = returns.add(1).prod() - 1  # 总收益率\n",
    "return_annualized = abs(total + 1.0) ** (1.0 / years) - 1  # 年化收益率\n",
    "# 计算年化标准差\n",
    "std_annualized = returns.std() * np.sqrt(annual_periods)\n",
    "# 计算夏普比率\n",
    "sharpe = return_annualized / std_annualized"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "4broker",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
